package controllers

import (
	"crypto/md5"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"net/http"
	"regexp"
	"user/models"
)

type RegisterController struct {
	beego.Controller
}

func (this *RegisterController) Register() {
	mobile := this.GetString("mobile")
	password := this.GetString("pwd")
	res := regexp.MustCompile(`^1356789\d{10}$`)
	req := regexp.MustCompile(`^\w{6-12}$`)
	if !res.MatchString(mobile) {
		this.Data["json"] = map[string]interface{}{
			"code":    http.StatusCreated,
			"message": "手机号不合法",
		}
		this.ServeJSON()
		return
	}
	if !req.MatchString(password) {
		this.Data["json"] = map[string]interface{}{
			"code":    http.StatusCreated,
			"message": "密码格式不正确",
		}
		this.ServeJSON()
		return
	}
	pwd := fmt.Sprintf("%v", md5.Sum([]byte(password)))
	_, err := models.Register(models.User{
		Mobile:   mobile,
		Password: pwd,
	})
	if err != nil {
		this.Data["json"] = map[string]interface{}{
			"code":    http.StatusCreated,
			"message": "注册失败",
		}
		this.ServeJSON()
		return
	}
	this.Data["json"] = map[string]interface{}{
		"code":    http.StatusOK,
		"message": "注册成功",
	}
	this.ServeJSON()
	return
}
